import React, { useEffect, useState } from "react";
import { CapsuleTabs, Image } from "antd-mobile";
import { SearchBar, DotLoading } from "antd-mobile";
import { useNavigate } from "react-router-dom";
import { Sticky, PullRefresh } from "react-vant";
import axios from "axios";
import "./index.scss";

const Index: React.FC = () => {
  interface TabItem {
    key: string;
    title: string;
    img: string;
    children?: Array<TabItem>;
    id?: string;
  }

  const navigate = useNavigate();
  const [lista, setLista] = useState<any>([]);
  const [list, setList] = useState<Array<number>>([]);
  const [finished, setFinished] = useState<boolean>(false);
  // console.log(import.meta.env.VITE_A);
  // console.log(import.meta.env.VITE_TITLE);

  const render = async () => {
    const resp = await axios.get("/api/tablist");
    const { code, tablist } = resp.data;
    if (code === 200) {
      setLista(tablist);
      // console.log("load base-config");
    } else {
      <DotLoading color="primary" />;
    }
  };

  useEffect(() => {
    render();
  }, []);

  const detail = (items: TabItem) => {
    navigate(`/details/` + items.id, { state: { items } });
  };
  const onLoadRefresh = async (isRefresh?: any) => {
    const data = await render();
    setList((v: any) => {
      const newList = isRefresh ? data : [...v, ...list];

      return newList;
    });
  };

  const onRefresh = async () => {
    setFinished(false);
    await onLoadRefresh(1);
    window.location.reload();
    render();
  };

  return (
    <div className="box">
      <Sticky offsetTop={0}>
        <header onClick={() => navigate("/search")}>
          <SearchBar placeholder="请输入内容" />
        </header>
        <p className="logo">可回看</p>
      </Sticky>

      <main>
        <CapsuleTabs defaultActiveKey="0">
          {lista.length > 0 &&
            lista.map((item: TabItem, index: number) => (
              <CapsuleTabs.Tab title={item.title} key={index}>
                <div className="tabs">
                  <PullRefresh onRefresh={onRefresh}>
                    {item.children &&
                      item.children.map((items: TabItem, indexs: number) => {
                        return (
                          <div
                            key={indexs}
                            className="context"
                            onClick={() => detail(items)}
                            onLoad={onLoadRefresh}
                          >
                            <dl>
                              <dt className="img">
                                <Image lazy src={items.img} />
                              </dt>
                              <dd>{items.title}</dd>
                            </dl>
                          </div>
                        );
                      })}
                  </PullRefresh>
                </div>
              </CapsuleTabs.Tab>
            ))}
        </CapsuleTabs>
      </main>
    </div>
  );
};
export default Index;
